#include "head.h"

// 建立连接
int establishConnect(char *ip, char *port){
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = inet_addr(ip);
    saddr.sin_port = htons(atoi(port));

    int ret = connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
    ERROR_CHECK(ret, -1, "connect");

    return sockfd;
}

// 请求
int TLVRequest(int sockfd, char *buf, int type){

    train_t train;
    bzero(&train, sizeof(train));
    
    if(buf == NULL){
        train.len = 0;
    }else{
        train.len = strlen(buf);
        memcpy(train.path, buf, train.len);
    }
    train.type = type;

    send(sockfd, &train, sizeof(int) * 3 + train.len, MSG_NOSIGNAL);

    return 0;
}

// 功能：传送一个带参数的指令
int TLVRequestSign(int sockfd, char *buf, int type, bool *args){
    train_t train;
    bzero(&train, sizeof(train));

    train.type = type;
    if(buf == NULL){
        train.len = 0;
    }else{
        train.len = strlen(buf);
        memcpy(train.path, buf, train.len);
    }
    
    // 参数处理
    for(int i = 0; i < 4; i++){
        train.args[i] = args[i];
    }
    
    send(sockfd, &train, sizeof(int) * 3 + train.len, MSG_NOSIGNAL);
    return 0;
}

// 功能：发送文件长度
int TLVRequestLen(int sockfd ,int len){
    train_t train;
    bzero(&train, sizeof(train));

    train.len = len;
    train.type = FILE_LEN;
    send(sockfd, &train, sizeof(int) *3, MSG_NOSIGNAL);
    return 0;
}


// 接收来自服务端的响应
int recvResponse(int sockfd){
    train_t train;
    bzero(&train, sizeof(train));

    recv(sockfd, &train.type, sizeof(train.type), MSG_WAITALL);
    recv(sockfd, &train.args, sizeof(int), MSG_WAITALL);
    recv(sockfd, &train.len, sizeof(train.len), MSG_WAITALL);
    recv(sockfd, train.path, train.len, MSG_WAITALL);
    printf("server talk : %s\n", train.path);
    // 返回状态码
    /* printf("type : %d", train.type); */
    return train.type;
}

// 身份验证
int idVerify(int sockfd){
    while(1){

        // 传送名字
        char name[256] = {0};
        char password[256] = {0};
        
        // 从标准输入读取数据
        printf("请输入用户名:\n");
        scanf(" %s", name);
        if(strlen(name) >= 50){
            printf("用户名不规范\n");
            continue;
        }
        printf("请输入密码:\n");
        scanf(" %s", password);
        if(strlen(password) >= 30 || strlen(password) < 8){
            printf("密码不规范,重新输入\n");
            continue;
        }

        // 传送用户名
        TLVRequest(sockfd, name, LOGIN_NAME);

        // 传送密码
        TLVRequest(sockfd, password, LOGIN_PASSWORD);

        // 接收来自服务端的响应
        if(recvResponse(sockfd) == IS_OK){
            return 0;
        }
    }
    return 0;
}



